/*
 * Main file that prints the BRAIN OS header, as well as prompting
 * the user for file input.  Also parses the brain file.
 * 
 * main.c
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mailman.h"
#include "semaphore.h"
#include "BRAIN10.h"
#include "scheduler.h"
#include "instructions.h"
 

FILE *brainFile;            // BRAIN10 program file

int main(void)
{
    // Create BRAIN10 machines and scheduler
    BRAIN10 *brain10 = malloc(sizeof(BRAIN10));         // BRAIN10 Machine
    VBRAIN10 *vbrain10 = malloc(sizeof(VBRAIN10));      // BRAIN10 VMachine
    MAILMAN *mailman = malloc(sizeof(MAILMAN));         // BRAIN10 MAILMAN
    SEMAPHORES *semaphores = malloc(sizeof(SEMAPHORES));   // BRAIN10 SEMAPHORES

    // Start the BRAIN10 virtual and physical machines
    initiateBrain(brain10);
    initiateMailMan(mailman);
    initiateVBrain(vbrain10);
    initiateSemaphores(semaphores);

    
    // Set the main directory to read from
    char directory[100] = "/home/brian/Desktop/";
    char fileName[30];
    
    printf("        _---~~(~~-_.        B\n");
    printf("     _{        )   )        R\n");
    printf("   ,   ) -~~- ( ,-' )_      A\n");
    printf("  (  `-,_..`., )-- '_,)     I\n");
    printf(" ( ` _)  (  -~( -_ `,  }    N\n");
    printf(" (_-  _  ~_-~~~~`,  ,' )    1\n");
    printf("   `~ -^(    __;-,((()))    0\n");
    printf("         ~~~~ {_ -_(())     \n");
    printf("                `\\  }       O\n");
    printf("                  { }       S\n\n");
    
    printf("Welcome to the BRAIN10 Operating System!\n");
    printf("Please enter the BRAIN10 file you would like to execute: ");
    scanf("%s", fileName);

    strcat(directory, fileName);
    //Open the BRAIN10 file
    brainFile = fopen(directory, "r");
    
    // Exit if BRAIN10 file not found
    if (!brainFile)
    {
        printf("Couldnt open BRAIN10 file! >:(");
        exit(EXIT_FAILURE);
    }

    // Begin reading BRAIN10 file
    char fileLine[100];
    fgets(fileLine, sizeof(fileLine), brainFile);
    int lineNum = 0;
    // While we haven't reached DATA
    while (strncmp(fileLine, "DATA", 4) != 0)
    {
        int numChars = strlen(fileLine) - 1;
        handleLine(lineNum, fileLine, numChars, brain10, vbrain10);
        fgets(fileLine, sizeof(fileLine), brainFile);
        lineNum++;
    }

    // Import data
    int dataLine = 0;
    fgets(fileLine, sizeof(fileLine) + 1, brainFile);
    // While it is not the end of the file
    while (strncmp(fileLine, "END", 3) != 0)
    { 
        handleData(dataLine, fileLine, brain10);
        fgets(fileLine, sizeof(fileLine) + 1, brainFile);
        dataLine++;
    }

    printf("End of BRAIN10 file...\n");

    beginScheduling(brain10, vbrain10, mailman, semaphores);

    //printMem(vbrain10);
}
